/**
 * Copyright 2009 by Christian Scheid. This file is part of the switch eclipse plugin and is licensed under the GPL
 * version 3. Please refer to the URL http://www.gnu.org/licenses/gpl-3.0.html for details.
 */
package org.digitalsoul.switchplugin;

import org.digitalsoul.switchplugin.model.ISwitchFile;
import org.digitalsoul.switchplugin.model.ISwitchItem;
import org.digitalsoul.switchplugin.model.ItemRing;

import java.util.Iterator;


public class Finder {

    /**
     * @param currentFile
     * @param currentPattern
     * @param patterns
     * @return
     */
    public ISwitchFile findNextFile(ISwitchFile currentFile, ItemRing items) {

        ISwitchFile matchingFile = null;
        ISwitchItem current = findMatch(currentFile, items);
        items.spoolTo(current);
        if (current != null) {
            Logger.log("Found current matching Switch Item '" + current + "'");
            Iterator<ISwitchItem> itemsIt = items.iterator();
            while (itemsIt.hasNext()) {
                ISwitchItem switchItem = itemsIt.next();
                matchingFile = switchItem.applyActions(currentFile);
                currentFile = matchingFile;
                if (matchingFile.exists()) {
//                    Logger.log("Switched to file '" + matchingFile + "'");
                    break;
                }
                else {
                    Logger.log("Could not switch to non-existing file '" + matchingFile  + "'");
                }
            }
        }
        else {
            Logger.log("Could not find any matching Switch Item");
        }
        return matchingFile;
    }

    /**
     * @param file
     * @param items
     * @return
     */
    protected ISwitchItem findMatch(ISwitchFile file, ItemRing items) {
        ISwitchItem foundItem = null;
        int numMatches = 0;
        for (ISwitchItem item : items) {
            if (item.matches(file)) {
                if (item.getLastNumberOfMatches() > numMatches) {
                    numMatches = item.getLastNumberOfMatches();
                    foundItem = item;
                }
            }
        }
        return foundItem;
    }
}
